<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
  <title>kf</title>
  <link rel="stylesheet" href="__PUBLIC__bootstrap/css/bootstrap.min.css">
  <link rel="stylesheet" href="__PUBLIC__font-awesome/css/font-awesome.min.css">
  <link rel="stylesheet" href="__PUBLIC__kf.css">
</head>
<body>
	<a href="{:U('Login/logout')}">注销</a>

	<ul class="kflist">

	</ul>

<div id="chat">
	<div class="chat-title">
		<span class="choose"></span>
	</div>

	<div class="chat-main">

	</div>

	<div class="chat-toolbar"></div>
	<div class="chat-textarea">
		<textarea name="" class="send_content" id="" cols="30" rows="10"></textarea>
	</div>
	<div class="chat-foot">

		<div class="btns">
			<button class="btn btn-success btn-xs send_btn">发送</button>
		</div>
	</div>
</div>


<div class="user visitor">
    <ul class="list">

    </ul>
</div>
<div class="user member">
    <ul class="list">

    </ul>
</div>

<script src="__PUBLIC__/jquery-1.11.0.min.js"></script>
<script src="__PUBLIC__bootstrap/js/bootstrap.min.js"></script>
<script src="__PUBLIC__/phpjs.js"></script>

<script src="__PUBLIC__/websocket/web_socket.js"></script>
<script src="__PUBLIC__/websocket/swfobject.js"></script>
<script src="__PUBLIC__/json.js"></script>
<script src="__PUBLIC__/jquery.im.js"></script>

<script>
WEB_SOCKET_SWF_LOCATION = "__PUBLIC__/websocket/WebSocketMain.swf";
WEB_SOCKET_DEBUG = true;

var uid = '{$Think.session.user.id}';
var token = '{$Think.session.user.token}';
var timeid, account, password, token, uid, onlines = [], ws;

var chat_time = 0;
var visitor = [], member = [];
var visitor_chat_time = [], member_chat_time = [];

var choose_uid, choose_cid;

function init() {
    ws = new WebSocket('ws://115.28.167.223:9999');
    ws.onopen = function () {
        timeid && window.clearInterval(timeid);
        ws.send(JSON.stringify({"type": "kflogin", "uid": uid, "token": token}));
    };

    ws.onmessage = function (e) {
        console.log(e.data);
        try {
            var data = JSON.parse(e.data);
            switch (data['type']) {
                // 当前用户登录结果返回
                case 'loginResult':

                    if (data['code'] == -1) {
                        console.log('登录失败：' + data['msg']);
                        window.location.href = '{:U("Login/logout")}';
                    } else if (data['code'] == 0) {
                        ws.send(JSON.stringify({"type": "kflist"}));
                        console.log('登录成功');
                    }

                    break;

                // 用户登录消息
                case 'login':

                    if (data['identity'] == 'kf') {
                        kf_append(data);
                        console.log('客服 ' + data['nickname'] + ' 上线了');
                    }

                    break;

                // 用户退出消息
                case 'logout':

                    if (data['identity'] == 'kf') {
                        $('#kf-' + data.uid).remove();
                        console.log('客服 ' + data['nickname'] + ' 下线了');
                    }

                    break;

                // 客户列表
                case 'kflist':

                    if (data['list'].length > 0) {

                        $.each(data.list, function (index, val) {
                            kf_append(val);
                        });

                    }

                    break;

                case 'message':

                    receive_message(data);

                    break;

            }
        } catch (err) {

        }

    };
    ws.onclose = function () {
        console.log("连接关闭，定时重连");
        // 定时重连
        window.clearInterval(timeid);
        timeid = window.setInterval(init, 3000);
    };
    ws.onerror = function () {

    };
}
init();

function kf_append(data) {

    if ($("#kf-" + data.uid).length <= 0) {
        $('.kflist').append('<li id="kf-' + data.uid + '" data-uid="' + data.uid + '" data-client-id="' + data.client_id + '">' + data.nickname + '</li>');
    } else {
        $("#kf-" + data.uid).attr({
            'data-client-id': data.client_id
        });

        $("#kf-" + data.uid).html(data.nickname);
    }

}

function visitor_append(data) {

    if ($("#visitor-" + data.client_id).length <= 0) {

        $('.visitor .list').append('<li class="new-message" id="visitor-' + data.client_id + '" data-client-id="' + data.client_id + '">' + data.nickname + '</li>');

    } else {
        if (choose_cid != data.client_id) {
            $("#visitor-" + data.client_id).addClass('new-message');
        }
    }
}


function judge_chat_time(array, chat_time_obj, id) {
    var now_time = time();
    var chat_time = chat_time_obj[id];
    if ((now_time - chat_time) > 5 * 60) {

        array.push('<div class="chat_time">' + date("H:i:s", now_time) + '</div>');
        chat_time_obj[id] = now_time;
    }

}

function receive_message(data) {
//    [{"identity":"anonymous","uid":0,"client_id":696,"nickname":"\u6e38\u5ba2696","time":1439257291}],"message":"asa"}
    var from = data.from[0];

    if (from.identity == "anonymous") {

        var cid = from.client_id;

        if (typeof visitor[cid] == "undefined") {

            visitor[cid] = [];
            visitor_chat_time[cid] = 0;
        }

        visitor_append(from);
        judge_chat_time(visitor[cid], visitor_chat_time, cid);

        visitor[cid].push('<div class="message"><span class="left">' + htmlspecialchars(data.message) + '</span></div>');

        if (choose_cid == cid) {

            show_message(visitor[cid]);
        }
    } else {


    }


}

function show_message(data) {

    $('.chat-main').html('');
    $.each(data, function (index, val) {
        $('.chat-main').append(val);
    });

    var scrollTop = $(".chat-main")[0].scrollHeight;
    $(".chat-main").scrollTop(scrollTop);
}


$(document).on('click', '.visitor li', function (event) {

    $(this).removeClass('new-message');

    choose_cid = $(this).attr('data-client-id');
    choose_uid = 0;

    $('.choose').html('当前选择用户：' + $(this).html());

    show_message(visitor[choose_cid]);
})

$(document).on('click', '.send_btn', function () {

    if (!choose_cid && !choose_uid) {
        alert('请选择用户');
        return false;
    }

    var message = $('.send_content').val();
    if (message == '') {
        return false;
    }

    $('.send_content').val('');

    var my_message = '<div class="message"><span class="right">' + htmlspecialchars(message) + '</span></div>';
    if (choose_cid) {
        judge_chat_time(visitor[choose_cid], visitor_chat_time, choose_cid);
        visitor[choose_cid].push(my_message);
        show_message(visitor[choose_cid]);
    } else {
        judge_chat_time(member[choose_uid], member_chat_time, choose_uid);
        member[choose_uid].push(my_message);
        show_message(member[choose_uid]);
    }

    ws.send(JSON.stringify({"type": "send", "to": choose_cid, "touid": choose_uid, "message": message}));
})

</script>

</body>
</html>